package com.ruoyi.backend.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.ruoyi.backend.mapper.ShopServiceMapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.SysUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.backend.mapper.ShopMapper;
import com.ruoyi.backend.domain.Shop;
import com.ruoyi.backend.service.IShopService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 店铺Service业务层处理
 * 
 * @author wjr
 * @date 2025-09-23
 */
@Service
public class ShopServiceImpl implements IShopService 
{
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private ShopServiceMapper shopServiceMapper;

    /**
     * 查询店铺
     * 
     * @param id 店铺主键
     * @return 店铺
     */
    @Override
    public Shop selectShopById(Integer id)
    {
        return shopMapper.selectShopById(id);
    }

    /**
     * 查询店铺列表
     * 
     * @param shop 店铺
     * @return 店铺
     */
    @Override
    public List<Shop> selectShopList(Shop shop)
    {
        return shopMapper.selectShopList(shop);
    }

    /**
     * 新增店铺
     * 
     * @param shop 店铺
     * @return 结果
     */
    @Override
    @Transactional
    public int insertShop(Shop shop)
    {
        shop.setCreateBy(SecurityUtils.getUsername());
        shop.setCreateTime(DateUtils.getNowDate());
        int result = shopMapper.insertShop(shop);

        //新增店铺服务表数据
        Integer[] serviceIds = shop.getServiceIds();
        if (serviceIds != null && serviceIds.length > 0) {
            // 新增用户与角色管理
            shopServiceMapper.batchInsertShopService(shop.getId(), serviceIds);
        }
        return result;
    }

    /**
     * 修改店铺
     * 
     * @param shop 店铺
     * @return 结果
     */
    @Override
    @Transactional
    public int updateShop(Shop shop)
    {
        //先删除店铺服务表数据
        shopServiceMapper.deleteShopServiceByShopId(shop.getId());
        //新增店铺服务表数据
        Integer[] serviceIds = shop.getServiceIds();
        if (serviceIds != null && serviceIds.length > 0) {
            // 新增用户与角色管理
            shopServiceMapper.batchInsertShopService(shop.getId(), serviceIds);
        }

        shop.setUpdateBy(SecurityUtils.getUsername());
        shop.setUpdateTime(DateUtils.getNowDate());
        return shopMapper.updateShop(shop);
    }

    /**
     * 批量删除店铺
     * 
     * @param ids 需要删除的店铺主键
     * @return 结果
     */
    @Override
    public int deleteShopByIds(Integer[] ids)
    {
        return shopMapper.deleteShopByIds(ids);
    }

    /**
     * 删除店铺信息
     * 
     * @param id 店铺主键
     * @return 结果
     */
    @Override
    public int deleteShopById(Integer id)
    {
        return shopMapper.deleteShopById(id);
    }
}
